package com.hmall.search.service.impl;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SearchService implements ISearchService {
    @Autowired
    private RestHighLevelClient client;

    /**
     * 获取搜索内容
     * @return
     * @throws IOException
     */
    @Override
    public Map<String, List<String>> list() throws IOException {

        SearchRequest request = new SearchRequest("hmall");

        // 编写DSL条件
        request.source().size(0);
        request.source().aggregations().addAggregator(
                AggregationBuilders.terms("brand").field("brand").size(10)
        );
        request.source().aggregations().addAggregator(
                AggregationBuilders.terms("category").field("category").size(10)
        );

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        // 处理数据
        Map<String, List<String>> map = new HashMap<>();

        ArrayList<String> category = getValue(response, "category");
        ArrayList<String> brand = getValue(response, "brand");

        map.put("brand", brand);
        map.put("category", category);
        return map;
    }

    /**
     * 封装获取返回结果中的bucket数据
     * @param response
     * @param aggName
     * @return
     */
    private ArrayList<String> getValue(SearchResponse response, String aggName) {
        Aggregations aggregations = response.getAggregations();

        // 注意：要将接收结果的类型手动改为Terms，因为我们设置DSL查询条件时是通过Terms类型做查询的
        Terms terms = aggregations.get(aggName);

        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        ArrayList<String> list = new ArrayList<>();
        for (Terms.Bucket item : buckets) {
            String value = item.getKeyAsString();
            list.add(value);
        }
        return list;
    }
}
